<?php
declare (strict_types=1);

namespace app\course\logic\classes;

use app\course\logic\base\CourseSection;
use app\course\model\classes\Classes as ClassesModel;
use app\user\logic\teacher\Teacher;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 后台管理逻辑层
 */
class Classes extends ClassesModel
{

    // 任教班级
    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getTeacherClasses($field = '*')
    {
        $teacher_id = app(Teacher::class)->isTeacher(request()->mid, true);
        return $this->field($field)->whereRaw('ext_data->"$.headmaster" = ' . $teacher_id)->withCount(['student'])->with(['cover_url'])->scope('classes,status,listingTime')->select();
    }

    // 班级课课时统计
    public function getClassesSectionCount($classes_id): int
    {
        // 课程IDs
        $ids = app(ClassesLink::class)->getCourseIds($classes_id);

        // 班级课时
        return app(CourseSection::class)->where('course_id', 'IN', $ids)->where('is_last', 1)->where('status', 1)->count();
    }

    /**
     * getClassesTeachers
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/07/21
     *
     * @param $classesId
     * @return Teacher[]|array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getClassesTeachers($classesId)
    {
        $teacherIds = app(ClassesLink::class)->alias('l')->join('course c', 'c.id=l.course_id AND l.classes_id=' . $classesId)->field('teacher_id')->buildSql();

        return app(Teacher::class)->field('id,user_id')->with(['teacher_name', 'teacher_avatar'])->whereRaw('id IN ' . $teacherIds)->select();
    }
}
